package com.henanuniversity.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@WebServlet("/")
public class DispatchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //进行乱码的处理
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //response.setContentType("text/html;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");

        //获取客户端的请求路径
        String path=request.getServletPath();
        System.out.println(path);
        String className=path.substring(1,path.lastIndexOf("/"));
        System.out.println(className);
        String methodName=path.substring(path.lastIndexOf("/")+1);
        System.out.println(methodName);
        PrintWriter out=null;

        try {
            Class clazz= Class.forName("com.henanuniversity.controller." + className);
            Object controller = clazz.newInstance();
            Method method=clazz.getMethod(methodName,new Class[]{HttpServletRequest.class,HttpServletResponse.class});
            //调用上面找到的方法
            Object result=method.invoke(controller,new Object[]{request,response});
            out = response.getWriter();
            ObjectMapper om=new ObjectMapper();
            out.print(om.writeValueAsString(result));

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
           // out.close();
        }


    }
}
